package com.cloudxingkong.dianyinke.VideoPlay;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.cloudxingkong.dianyinke.R;
import com.cloudxingkong.dianyinke.Student.bean.VideoTeacherEntity;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class VideoPlay extends AppCompatActivity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener {
    private RelativeLayout topLayout;
    private RelativeLayout bottomLayout;
    private SurfaceView surfaceView;
    private ImageView btnPlay;
    private TextView system_time;
    private ImageView btnPause;
    private SeekBar seekBar;
    private TextView tvCurrent;
    private TextView tvDuration;
    private MediaPlayer mediaPlayer;
    private int count = 1;
    private boolean flag = true;
    private String videoPath;
    private TextView landplay_title,landplay_title_time;
    private String title,time;
    private RelativeLayout pbLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //屏幕常亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //没用
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        setContentView(R.layout.activity_video_play);
        init();
        //设置播放总时间的初始值
        tvDuration.setText("-00:00");
        //重置MediaPlayer
        mediaPlayer.reset();
        //设置监听
        surfaceView.getHolder().addCallback(this);
        surfaceView.getHolder().setKeepScreenOn(true);

        //进度条
        seekBar.setProgress(0);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {


                if (fromUser == true && mediaPlayer != null) {
                    mediaPlayer.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                seekBar.setProgress(0);
            }
        });


        try {
            //MediaPlayer设置资源
            mediaPlayer.setDataSource(this, Uri.parse(videoPath));
            Log.e("test","播放地址 "+videoPath);
            pbLayout.setVisibility(View.VISIBLE);
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    topLayout.setVisibility(View.VISIBLE);
                    bottomLayout.setVisibility(View.VISIBLE);
                }
            });


            mediaPlayer.setOnPreparedListener(this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 初始化
     */
    private void init() {
        topLayout = (RelativeLayout) findViewById(R.id.lanplay_top_layout);
        bottomLayout = (RelativeLayout) findViewById(R.id.lanplay_bottom_layout);
        surfaceView = (SurfaceView) findViewById(R.id.landplay_surface_view);
        btnPlay = (ImageView) findViewById(R.id.landplay_bottom_play);
        btnPause = (ImageView) findViewById(R.id.landplay_bottom_pause);
        seekBar = (SeekBar) findViewById(R.id.landplay_seekbar);
        tvCurrent = (TextView) findViewById(R.id.landplay_bottom_current_time);
        tvDuration = (TextView) findViewById(R.id.lanplay_bottom_duration);
        landplay_title = (TextView) findViewById(R.id.landplay_title);
        landplay_title_time = (TextView) findViewById(R.id.landplay_title_time);
        pbLayout = (RelativeLayout) findViewById(R.id.landplay_pb_layout);

        mediaPlayer = new MediaPlayer();
        Intent intent = getIntent();
        videoPath = intent.getStringExtra("videoPath");
        time = intent.getStringExtra("time");
        title = intent.getStringExtra("title");
        landplay_title.setText(title);
        landplay_title_time.setText(time);
    }

    /**
     * activity销毁时的操作
     */
    @Override
    protected void onDestroy() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        super.onDestroy();
    }

    /**
     * sufaceView在创建的时候的回调
     *
     * @param holder
     */
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (mediaPlayer != null) {
            mediaPlayer.setDisplay(holder);
        }
    }

    /**
     * sufaceView在改变的时候的回调
     */
    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    /**
     * sufaceView在销毁的时候的回调
     */
    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mediaPlayer != null) {
            mediaPlayer.release();
        }
    }

    /**
     * 开启子线程每隔1s发送一次广播
     */
    class MyThread extends Thread {
        @Override
        public void run() {
            while (flag) {
                sendBroadcast(new Intent("video"));
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //使用Handler设置正在播放的时间
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                String fm= (String) msg.obj;
                Log.e("test",fm);
                tvCurrent.setText(fm);
            }

        }
    };
    /**
     * mediaPlayer准备好播放的回调
     *
     * @param mp
     */
    @Override
    public void onPrepared(MediaPlayer mp) {


        int duration = mp.getDuration();
        long durL=duration;
        SimpleDateFormat format=new SimpleDateFormat("mm:ss");
        Date date = new Date(durL);
        String format1 = format.format(date);

        Log.e("test", "视频的长度 " + mp.getDuration()+" 视频时间格式化 "+format1);

        tvDuration.setText(format1);

        new Thread(){
            @Override
            public void run() {
                super.run();
                while (true){
                    try {
                        int currentPosition = mediaPlayer.getCurrentPosition();
                        long current=currentPosition;
                        SimpleDateFormat format=new SimpleDateFormat("mm:ss");
                        String fm=format.format(new Date(current));

                        Message msg=handler.obtainMessage();
                        msg.what=0;
                        msg.obj=fm;
                        handler.sendMessage(msg);
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }



            }
        }.start();


        pbLayout.setVisibility(View.GONE);
        /**
         * seekBar的操作
         */
        seekBar.setMax(mp.getDuration());
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser == true && mediaPlayer != null) {
                    mediaPlayer.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        new MyThread().start();
        registerReceiver(new VideoBroadReceiver(), new IntentFilter("video"));


        btnPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mediaPlayer.isPlaying()) {
                    mediaPlayer.start();
                    btnPlay.setVisibility(View.GONE);
                    btnPause.setVisibility(View.VISIBLE);
                    Log.e("test", mediaPlayer.getDuration() + "  <<<< 视频长度");
                }
            }
        });
        btnPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("test", mediaPlayer.isPlaying() + "  <<<<< 是否正在播放");
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                    btnPlay.setVisibility(View.VISIBLE);
                    btnPause.setVisibility(View.GONE);

                }
            }
        });
    }

    /**
     * 对seeckBar的广播
     */
    public class VideoBroadReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            seekBar.setProgress(mediaPlayer.getCurrentPosition());
        }
    }
    /**
     * activity的触摸事件监听
     *
     * @param event
     * @return
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        if (action == MotionEvent.ACTION_DOWN && mediaPlayer.isPlaying()) {
            count++;
            if (count % 2 == 0) {
                topLayout.setVisibility(View.GONE);
                bottomLayout.setVisibility(View.GONE);
            } else if (count % 2 == 1) {
                topLayout.setVisibility(View.VISIBLE);
                bottomLayout.setVisibility(View.VISIBLE);
            }
        }
        return super.onTouchEvent(event);
    }
    /**
     * 返回按钮
     *
     * @param view
     */
    public void landPlay(View view) {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer=null;
        }
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK) {
            if (mediaPlayer != null) {
                mediaPlayer.stop();
                mediaPlayer.release();
                mediaPlayer = null;
            }
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}

